import 'package:bwt_ad_flutter/manager/BwtAdManager.dart';
import 'package:flutter/services.dart';

import 'et/BwtAdLogType.dart';

class BwtAdCore {
  static const MethodChannel _channel = MethodChannel("bwt_ad_flutter");

  static const keyAppId = 'appId';
  static const keyIsRequestIdfa = 'isRequestIdfa';
  static const keyLogType = 'logType';
  static const keyWechatAppId = 'wechatAppId';
  static const keyPosId = 'posId';
  static const keyAdId = 'adId';
  static const keyAdEvent = 'adEvent';
  static const keyAdLoaderId = 'adLoaderId';
  static const keyAdx = 'adx';
  static const keyAdy = 'ady';
  static const keyAdWidth = 'adWidth';
  static const keyAdHeight = 'adHeight';
  static const keyAdBackground = 'adBackground';
  static const keyAdLogo = 'adLogo';
  static const keyAdMsg = 'adMsg';
  static const keyAdShowClose = 'adShowClose';

  static const methodInit = 'init';
  static const methodLoadSplashAd = 'loadSplashAd';
  static const methodLoadInterstitialAd = 'loadInterstitialAd';
  static const methodLoadNativeExpressAd = 'loadNativeExpressAd';
  static const methodRenderNativeExpressAd = 'renderNativeExpressAd';
  static const methodShowInterstitialAd = 'showInterstitialAd';
  static const methodLoadThenShowInterstitialAd = 'loadThenShowInterstitialAd';
  static const methodReleaseAd = 'releaseAd';
  static const methodOnAdEvent = 'onAdEvent';
  static const methodLoadBannerAd = "loadBannerAd";
  static const methodLoadServiceAd = "loadServiceAd";
  static const methodLoadNativeAd = "loadNativeAd";

  static const viewTypeBwtNativeExpressAd = 'BwtNativeExpressAd';
  static const viewTypeBwtBannerAd = 'viewTypeBwtBannerAd';
  static const viewTypeBwtServiceAd = 'viewTypeBwtServiceAd';
  static const viewTypeBwtNativeAd = 'viewTypeBwtNativeAd';

  BwtAdCore._();

  static bool _inited = false;

  /// 初始化广告SDK
  static Future<bool> init({
    required String appId,
    bool isRequestIdfa = true,
    BwtAdLogType logType = BwtAdLogType.NONE,
    String wechatAppId = '',
  }) async {
    if (_inited) return Future.value(true);

    // 设置事件监听
    _setupMethodCallHandler();
    // 通知原生初始化
    var success = await invokeMethod(method: methodInit, params: {
      keyAppId: appId,
      keyIsRequestIdfa: isRequestIdfa,
      keyLogType: logType.logName,
      keyWechatAppId: wechatAppId,
    });
    _inited = success;
    return Future.value(success);
  }

  /// 设置事件监听
  static void _setupMethodCallHandler() {
    _channel.setMethodCallHandler((MethodCall call) async {
      // 监听到了原生发送的事件
      if (methodOnAdEvent == call.method) {
        // 广告回调方法
        BwtAdManager.onAdEvent(arguments: call.arguments);
      }
    });
  }

  /// Flutter通知其他端
  static Future<bool> invokeMethod({
    required String method,
    Map<String, dynamic>? params,
  }) async {
    try {
      return await _channel.invokeMethod(method, params ?? {});
    } catch (e) {
      print(e);
    }
    return false;
  }
}
